﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Uniloader.Interface;
using Uniloader.Managers;
using System.IO;
using Microsoft.Win32;
using XamlTorrent.Common;

namespace XamlTorrent.Managers.UriGetter.UI
{
    /// <summary>
    /// Interaction logic for CreateUriTask.xaml
    /// </summary>
    public partial class CreateUriTask : UserControl, ITransferTaskFactory
    {
        public CreateUriTask(UriTransferManager manager)
        {
            transferManager = manager;

            InitializeComponent();
        }

        private UriTransferManager transferManager;

        string checksum = String.Empty;
        public string Checksum
        {
            get { return checksum; }
            set { checksum = value; }
        }

        string sourceUri = String.Empty;
        public string SourceUri
        {
            get { return sourceUri; }
            set { sourceUri = value; }
        }
        
        string savePathStr;
        public string SavePathStr
        {
            get { return savePathStr; }
            set { savePathStr = value; }
        }

        private void browseSavePath_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog saveTo = new OpenFileDialog();

            saveTo.FileName = savePath.Text;

            saveTo.Multiselect = false;

            if (saveTo.ShowDialog() ?? false)
                savePath.Text = saveTo.FileName;
        }

        #region ITaskGenerator Members

        public TransferTask CreateTask()
        {
            Uri sourceUri = null;
            FileInfo destPath = null;
            byte[] checkSum = null;
            string hashAlg = null;

            Uri.TryCreate(fileUri.Text, UriKind.Absolute, out sourceUri);
            destPath = new FileInfo(savePath.Text);

            if (!String.IsNullOrEmpty(fileChecksum.Text))
            {
                checkSum = new HexEncoding().GetBytes(fileChecksum.Text);
                hashAlg = hashAlgorithm.SelectedValue == null ? null : hashAlgorithm.SelectedValue.ToString();
            }

            UriDownloadTask task = new UriDownloadTask(sourceUri, destPath, checkSum, hashAlg);

            transferManager.AddTask(task);

            return task;
        }

        #endregion
    }
}
